package com.example.venadaoa.activity.setting;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;

import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.bumptech.glide.Glide;
import com.example.venadaoa.R;
import com.example.venadaoa.base.BaseActivity;
import com.example.venadaoa.datamanager.SystemInfo;
import com.example.venadaoa.datamanager.UserInfo;
import com.example.venadaoa.net.Api;
import com.example.venadaoa.net.NetUtils;
import com.example.venadaoa.tool.ToastHelp;
import com.mcxtzhang.commonadapter.lvgv.CommonAdapter;
import com.mcxtzhang.commonadapter.lvgv.ViewHolder;


import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * Created by Dell on 2017/7/13.
 */

public class AddressBookActivity extends BaseActivity implements OnItemClickListener, Filterable {
    private View main_view;


    private List<SystemInfo.UserListBean> userList;

    private ListView list;

    private EditText searchEt;

    private PersonFilter filter;

    private CommonAdapter<SystemInfo.UserListBean> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageName = "AddressBookActivity";
        LayoutInflater inflate = LayoutInflater.from(this);
        main_view = inflate.inflate(R.layout.address_book_view, null);
        setContentView(main_view);

        list = (ListView) main_view.findViewById(R.id.list);
        userList = SystemInfo.getSystemInfo(context).getUserList();

        adapter =new CommonAdapter<SystemInfo.UserListBean>(context,userList,R.layout.address_book_item) {
            @Override
            public void convert(ViewHolder viewHolder, SystemInfo.UserListBean userListBean, int i) {
                String name = userListBean.getName();
                String mobiephone = userListBean.getMobileNumber();

                TextView namestr = viewHolder.getView(R.id.true_name);

                TextView mobiephonestr =  viewHolder.getView(R.id.true_phone);

                namestr.setText(name);

                mobiephonestr.setText(mobiephone);

                ImageView imageView =  viewHolder.getView(R.id.people_pic);
                imageView.setImageResource(R.mipmap.mrtx);

                LoadHeadPic(imageView);
            }
        };
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);

        searchEt = (EditText) main_view.findViewById(R.id.searchbox);
        searchEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
                getFilter().filter(arg0); //这里传入数据就可以了
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }
        });


        // 返回键
        ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);

        backBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }


    private void LoadHeadPic(final ImageView imageView) {
        Map<String, String> params = new HashMap<>();
        params.put("userId", UserInfo.getUserInfor(context).getUserObject().getId());
        Api.getOtherPhoto(context, params, new NetUtils.NetCallBack<Bitmap>() {
            @Override
            public void success(Bitmap rspData) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                rspData.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] bytes=baos.toByteArray();
                Glide.with(context)
                        .load(bytes)
                        .bitmapTransform(new CropCircleTransformation(context)).crossFade(1000)
                        .placeholder(R.mipmap.mrtx)
                        .error(R.mipmap.mrtx)
                        .into(imageView);
            }

            @Override
            public void failed(String msg) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            public void run() {
                showSoftKeyboard();
            }

        }, 500);
    }

    public void hideSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
    }

    public void showSoftKeyboard() {
        InputMethodManager im = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        im.showSoftInput(searchEt, 0);
    }

    @Override
    public Filter getFilter() {
        if(filter ==null) {
            filter = new PersonFilter(SystemInfo.getSystemInfo(context).getUserList());
        }

        return filter;
    }

    private class PersonFilter extends Filter {
        private List<SystemInfo.UserListBean> userinfoLists = new ArrayList<>();

        public PersonFilter(List<SystemInfo.UserListBean> userinfoList) {
            this.userinfoLists = userinfoList;
            // TODO Auto-generated constructor stub
        }


        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint == null || constraint.length() == 0) {
                results.values = userinfoLists;
                results.count = userinfoLists.size();
            } else {
                List<SystemInfo.UserListBean> mList = new ArrayList<>();
                for (SystemInfo.UserListBean p : userinfoLists) {
                    if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase())
                            ) {
                        mList.add(p);
                    }
                }
                results.values = mList;
                results.count = mList.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            // TODO Auto-generated method stub
            adapter.setDatas((ArrayList<SystemInfo.UserListBean>) results.values);
        }

    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        final SystemInfo.UserListBean userinfoCatch = adapter.getItem(arg2);
        final AlertDialog roleDia = new AlertDialog.Builder(AddressBookActivity.this).create();
        roleDia.show();
        //View alertView = inflater.inflate(R.layout.choose_more_view, null);
        roleDia.getWindow().setContentView(R.layout.address_book_choose_view);

        TextView title = (TextView) roleDia.getWindow().findViewById(R.id.title);
        title.setText("你选择了" + userinfoCatch.getName());

        TextView cancelBtn = (TextView) roleDia.getWindow().findViewById(R.id.cancel_btn);
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                roleDia.dismiss();
            }
        });

        TextView phoneCallBtn = (TextView) roleDia.getWindow().findViewById(R.id.call_phone);
        phoneCallBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                String number = userinfoCatch.getMobileNumber();
                //用intent启动拨打电话
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    startActivity(intent);
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }


                roleDia.dismiss();
            }
        });

        TextView sendMsgBtn = (TextView) roleDia.getWindow().findViewById(R.id.send_msg);
        sendMsgBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                String number = userinfoCatch.getMobileNumber();
                Uri uri = Uri.parse("smsto:" + number);
                Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(sendIntent);

                roleDia.dismiss();
            }
        });

        TextView addToBook = (TextView) roleDia.getWindow().findViewById(R.id.add_address);
        addToBook.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (insert(userinfoCatch.getName(), userinfoCatch.getMobileNumber(), userinfoCatch.getEmail())) {

                    Toast.makeText(AddressBookActivity.this, "添加联系人成功", Toast.LENGTH_SHORT).show();
                } else {
                    ToastHelp.doToast(AddressBookActivity.this, "添加失败");
                }

                roleDia.dismiss();
            }
        });
    }

    public boolean insert(String given_name, String mobile_number,
                          String work_email) {
        try {
            /* 往 raw_contacts 中添加数据，并获取添加的id号*/
            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            ContentResolver resolver = getContentResolver();
            ContentValues values = new ContentValues();
            long contactId = ContentUris.parseId(resolver.insert(uri, values));

	        /* 往 data 中添加数据（要根据前面获取的id号） */
            // 添加姓名
            uri = Uri.parse("content://com.android.contacts/data");
            values.put("raw_contact_id", contactId);
            values.put("mimetype", "vnd.android.cursor.item/name");
            values.put("data2", given_name);
            resolver.insert(uri, values);

            // 添加电话
            values.clear();
            values.put("raw_contact_id", contactId);
            values.put("mimetype", "vnd.android.cursor.item/phone_v2");
            values.put("data2", "2");
            values.put("data1", mobile_number);
            resolver.insert(uri, values);

            // 添加Email
            values.clear();
            values.put("raw_contact_id", contactId);
            values.put("mimetype", "vnd.android.cursor.item/email_v2");
            values.put("data2", "2");
            values.put("data1", work_email);
            resolver.insert(uri, values);

            //Toast.makeText(AddressBookActivity.this, "添加成功", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
